package com.yutian.selfservice.support.upload.handler;

import com.yutian.selfservice.support.upload.config.UploadConfig;
import com.yutian.selfservice.support.upload.handler.storage.Storage;
import com.yutian.selfservice.support.utils.Result;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;

public class Upload {
    private Storage storage;
    private UploadConfig.UploadProperties uploadProperties;

    public Upload(Storage storage, UploadConfig.UploadProperties uploadProperties){
        this.storage = storage;
        this.uploadProperties = uploadProperties;
    }
    public Result upload(HttpServletRequest request){
        Collection<MultipartFile> files = ((MultipartHttpServletRequest) request).getFileMap().values();
        if(CollectionUtils.isEmpty(files)){
            return Result.fail("文件为空");
        }
        return upload(new ArrayList<>(files).get(0));
    }

    /**
     * 上传单个文件
     *
     * @param multipartFile
     * @return
     */
    Result upload(MultipartFile multipartFile){
        return this.storage.storage(multipartFile,uploadProperties);
    }
}
